<?php
namespace App\Library;

use App\Http\Config\WechatAPI;
use App\Models\Admin\Configs;
use Illuminate\Filesystem\Cache;

/**
 * @author Tech
 */
class WeChat
{
    public static function getToken(){
//        $access_token = Cache::get('weChatApp_access_token');
//        if ($access_token == null) {
            $con = Configs::query()->where("mall_id", request()->mallData["id"])->first();
            $get_token_res = self::curl(WechatAPI::$wechat_conf["get_token"]."&appid={$con->member_wechat_appid}&secret={$con->member_wechat_secret}");
            $get_token_res = json_decode($get_token_res, true);
            if(empty($get_token_res['access_token'])) {
                return false;
            }
//            Cache::pull('weChatApp_access_token', $get_token_res["access_token"], $get_token_res["expires_in"]);
            $access_token = $get_token_res['access_token'];
//        }
        return $access_token;
    }

    public static function sendTemplateMsg($openid, $template_id, $param = [], &$msg = ''){
        $token = self::getToken();
        if (!$token) {
            $msg = "获取token失败";
            return false;
        }
        $data = [
            'touser' => $openid,
            'template_id' => $template_id,
//            'page' => "",
            'data' => $param
        ];
        $result = self::curl("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$token}", json_encode($data, JSON_FORCE_OBJECT));
        $result = json_decode($result, true);
        if($result['errcode'] !== 0){
            $msg = "token：{$token} 发送模板消息出错：错误码：$result[errcode]；错误消息：$result[errmsg]；".var_export($data, true);
            return false;
        }
        return $result;
    }

    public static function curl($url, $data = "", $header = ['Content-Type: application/json'], $timeout = 60)
    {
        $ch = curl_init($url);
        if(empty($data)){
            curl_setopt($ch, CURLOPT_HTTPGET, 1);
        }else {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        if(!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $output = curl_exec($ch);
        $errno = curl_errno($ch);
        if ($errno) {
//            $info  = curl_getinfo( $ch );
//            $info['errno'] = $errno;
            curl_close($ch);
            return false;
        }
        curl_close($ch);
        return $output;
    }
}